/**
 * Created by tanbingqin on 2020/10/6.
 * 新的外部参与人姓名控件 messageKey为out_participant_full_name
 */
import {messages} from "share/common";
import React from 'react'
import { connect } from 'react-redux'
import { Button, Modal, Popover, Row, Col, Icon, Input, message } from 'antd'

import 'styles/request/custom-field/external-participant-name.scss'

class ExternalName extends React.Component{
  constructor(props) {
    super(props);
    this.state = {
      modalVisible: false,
      nameList: []
    }
  }

  componentDidMount() {}

  componentWillReceiveProps(nextProps) {};

  showModal = (isOpen, isSubmit) => {
    const { nameList } = this.state;
    const { onChange, value } = this.props;
    if (isOpen) {
      if (value) {
        this.setState({nameList: JSON.parse(value)});
      } else {
        this.setState({
          nameList: [
            {
              name: '',
              enLastName: '',
              enFirstName: ''
            }
          ]
        });
      }
    }

    if (isSubmit) {
      let length = nameList.length;
      let i = 0;
      for (i; i < length; i++) {
        let item = nameList[i];
        if (!item.name && !item.enFirstName && !item.enLastName) {
          message.error(messages('request-1.key841',{arg1: i+1})/*请填写参与人{arg1}的姓名*/);
          return;
        }
        if (item.enFirstName && !item.enLastName) {
          message.error(messages('request-1.key842',{arg1: i+1})/*请填写参与人{arg1}的姓（拼音）*/);
          return;
        }
        if (!item.enFirstName && item.enLastName) {
          message.error(messages('request-1.key843',{arg1: i+1})/*请填写参与人{arg1}的名（拼音）*/);
          return;
        }
      }
      onChange(length ? JSON.stringify(nameList) : '');
      this.setState({modalVisible: isOpen});
    } else {
      this.setState({modalVisible: isOpen});
    }
  };

  handleChange = (value, index, key) => {
    let { nameList } = this.state;
    if ((key === 'enFirstName' || key === 'enLastName') && value.match(/[\u4E00-\u9FA5]/g)) {
      return;
    }
    nameList[index][key] = value;
    this.setState({nameList});
  };

  handleAdd = () => {
    let { nameList } = this.state;
    nameList.push({
      name: '',
      enLastName: '',
      enFirstName: ''
    });
    this.setState({nameList});
  };

  handleRemove = (index) => {
    let { nameList } = this.state;
    nameList.splice(index, 1);
    this.setState({nameList});
  };

  processNameStr = () => {
    const { value } = this.props;
    let nameList = value ? JSON.parse(value) : [];
    let placeholder = this.props.placeholder || messages('common.please.input');
    let str = '';
    let strList = [];
    nameList.forEach(item => {
      let itemStr = '';
      if (item.name && item.enFirstName && item.enLastName) {
        itemStr = `${item.name} | ${item.enLastName} ${item.enFirstName}`;
      }
      if (item.name && !item.enFirstName && !item.enLastName) {
        itemStr = item.name;
      }
      if (!item.name && item.enFirstName && item.enLastName) {
        itemStr = `${item.enLastName} ${item.enFirstName}`;
      }
      strList.push(itemStr);
    });
    str = strList.join(',');
    return {
      str: str || placeholder,
      isHasStr: !!str
    };
  };

  render() {
    const { disabled } = this.props;
    const { modalVisible, nameList } = this.state;
    let className = this.classNames([
      'ant-input',
      { 'ant-input-disabled': disabled },
      { 'placeholder': !this.processNameStr().isHasStr}
    ]);
    return (
      <div className="external-name-new">
        <div className={className} onClick={() => disabled ? {} : this.showModal(true)}>
          {this.processNameStr().str}
        </div>
        <Modal
          title={messages('request-1.key844')/*外部参与人*/}
          wrapClassName="external-name-modal"
          width={760}
          footer={
            <div>
              <Button onClick={() => this.showModal(false)}>{messages('common.cancel')/*取消*/}</Button>
              <Button
                type="primary"
                onClick={() => this.showModal(false, true)}
              >
                {messages('common.ok')/*确定*/}
              </Button>
            </div>
          }
          visible={modalVisible}
          onCancel={() => this.showModal(false)}
        >
          <div className="name-list-block">
            {!!nameList.length && (
              <Row type="flex" align="middle" gutter={16} className="margin-bottom-12">
                <Col span={5} offset={3}>
                  {messages('request-1.key845')/*中文姓名*/}
                </Col>
                <Col span={7}>
                  {messages('request-1.key846')/*姓（拼音）*/}
                </Col>
                <Col span={7}>
                  {messages('request-1.key847')/*名（拼音）*/}
                </Col>
              </Row>
            )}
            {nameList.map((item, index) => {
              return (
                <Row type="flex" align="middle" gutter={16} className="margin-bottom-12">
                  <Col span={3} className="label">{messages('request-1.key848')/*参与人*/}{index + 1}</Col>
                  <Col span={5}>
                    <Input
                      placeholder={messages('common.please.input')}
                      maxLength="24"
                      value={item.name}
                      onChange={e => this.handleChange(e.target.value, index, 'name')}
                    />
                  </Col>
                  <Col span={7}>
                    <Input
                      placeholder={messages('request-1.key849')/*Last Name,如LI*/}
                      maxLength="24"
                      value={item.enLastName}
                      onChange={e => this.handleChange(e.target.value, index, 'enLastName')}
                    />
                  </Col>
                  <Col span={7}>
                    <Input
                      placeholder={messages('request-1.key850')/*First Name,如MIN*/}
                      maxLength="24"
                      value={item.enFirstName}
                      onChange={e => this.handleChange(e.target.value, index, 'enFirstName')}
                    />
                  </Col>
                  <Col span={2}>
                    <Icon type="delete" className="icon-btn" onClick={() => this.handleRemove(index)}/>
                  </Col>
                </Row>
              )
            })}
            <Row type="flex" align="middle" gutter={16} className="margin-bottom-12">
              <Col span={12} offset={3}>
                <Button onClick={this.handleAdd}>
                  <Icon type="plus" />
                  {messages('request-1.key844')/*外部参与人*/}
                </Button>
              </Col>
            </Row>
          </div>
        </Modal>
      </div>
    )
  }
}

ExternalName.propTypes = {
  disabled: React.PropTypes.bool,
  onChange: React.PropTypes.func,
  placeholder: React.PropTypes.string
};

function mapStateToProps() {
  return {

  }
}

export default connect(mapStateToProps)(ExternalName)
